<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\GrGood;
use App\Models\GrRefund;
use App\Models\GrUser;

use App\Models\GrUserMember;

use App\Models\OrderGood;
use App\Models\Orders;
use App\Models\Store;
use App\service\FullDiscountStrategy;
use App\service\FullReductionStrategy;
use App\service\JwtService;
use App\service\Order\ReduceStock;
use App\service\Pay;
use App\service\ReturnService;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class OrderGoods extends Controller
{
    /**
     * 查询所有商品
     */
    public function allGoods()
    {

        $data = GrGood::all()->toArray();
        if ($data) {
            return ReturnService::successReturn('200', '成功', $data);
        } else {
            return ReturnService::failedReturn('400', '失败');
        }
    }

    /**
     * 详情页面
     */
    public function detail(Request $request)
    {
        //获取数据
        $goods_id = $request->get('goods_id');
        if (!empty($goods_id)) {
            $res = GrGood::where('goods_id', $goods_id)->first()->toArray();
            if ($res) {
                return ReturnService::successReturn('200', '成功', $res);
            } else {
                return ReturnService::failedReturn('400', '查询失败');
            }
        }
    }

    /**
     * 去购买
     */
    public function runBuy(Request $request)
    {
        $num = $request->get('num');
        $goods_id = $request->get('goods_id');
        $data = GrGood::where('goods_id', $goods_id)->first();
        $data['number'] = $num;
        if ($data) {
            return ReturnService::successReturn('200', '成功', $data);
        } else {
            return ReturnService::failedReturn('400', '失败');
        }
    }

    /**
     * 收货地址
     */
    public function address(Request $request)
    {
        //获取token
        $token = $request->get('token');
        $jwtData = JwtService::decodeToken($token);
        $user_id = $jwtData->data;
        $data = Address::where('user_id', $user_id)->get()->toArray();
        if ($data) {
            return ReturnService::successReturn('200', '成功', $data);
        }
    }

    /**
     * 打折
     */
    public function discount(Request $request){
        //获取token
        $token = $request->get('token');
        $jwtData = JwtService::decodeToken($token);
        $user_id = $jwtData->data;
        $data=Orders::where('user_id',$user_id)->where('is_pay',1)->sum('total_money');
        $member=GrUserMember::all()->toArray();
        foreach ($member as $k=>$v){
            if($data>=$v['lower_money']&&$data<=$v['hight_money']){
                return ReturnService::successReturn('200','成功',$v['discoun']);
            }else{
                if($data>=17000){
                    return ReturnService::successReturn('200','成功',0.90);
                }
            }
        }


    }



    /**
     * 确认订单
     */
    public function affirmOrder(Request $request)
    {
        //获取数据
        $data = $request->post();
        $goods_id = $data['goods_id'];
        $address_id = $data['address_id'];
        $num = $data['num'];
        $totalMoney = $data['totalMoney'];
        $discountMoney = $data['discountMoney'];
        $token = $data['token'];
        // 启动事务
        DB::beginTransaction();
        try {
            $jwtData = JwtService::decodeToken($token);
            $user_id = $jwtData->data;
            //雪花算法生成
            $snowflake = new Snowflake();
            $order_sn = $snowflake->id();
            //生成订单
            $data = [
                'user_id' => $user_id,
                'order_sn' => $order_sn,
                'goods_money' => $totalMoney,
                'total_money' => $discountMoney,
                'address_id' => $address_id,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $order_id = Orders::insertGetId($data);
            if ($order_id) {
                Redis::setex('order', '6000', serialize($data));
            }
//            $data=unserialize(Redis::get('order'));
            //生成订单商品表
            $orderGoods = new \App\service\Order\OrderGoods();
            $res = $orderGoods->orderGoods($order_id, $goods_id, $num);
            // 提交事务
            Db::commit();
            if ($res) {
                $data = GrGood::where('goods_id', $goods_id)->first()->toArray();
                $newNumber = $data['stock_total'] - $num;
                GrGood::where('goods_id', $goods_id)->update(['stock_total' => $newNumber]);
                $result = Orders::join('gr_order_goods', 'order.id', '=', 'gr_order_goods.order_id')
                    ->join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')
                    ->join('gr_user_address', 'order.address_id', '=', 'gr_user_address.id')->where('order.id', $order_id)->first();
                return ['code' => 200, 'message' => '成功', 'data' => $result];
            } else {
                return ['code' => 100, 'message' => '失败'];
            }
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
        }
    }
    //判断此订单是否已经成功
    public function is_balance_pay(Request $request){
        $data=$request->all();
        //获取user_id
        $jwtData = JwtService::decodeToken($data['token']);
        $user_id = $jwtData->data;
        $res= Orders::where('order_sn',$data['order_sn'])->where('user_id',$user_id)->first();
        if($res->is_pay==1){
            return ReturnService::successReturn('200','已支付',[]);
        }else{
            return ReturnService::failedReturn('400','未支付');
        }
    }

    /**
     * 余额支付
     */
    public function balancePay(Request $request)
    {
        //获取user_id
        $token = $request->post('token');
        $jwtData = JwtService::decodeToken($token);
        $user_id = $jwtData->data;
        $data = GrUser::where('id', $user_id)->first()->toArray();
        //获取余额
        $balance = $data['balance'];
        //获取支付密码
        $payment_code = $data['payment_code'];
        if ($payment_code != md5($request->post('password'))) {
            return ReturnService::failedReturn('401', '密码错误');
        } else {
            $order_sn = $request->post('order_sn');
            //开始
            DB::beginTransaction();
            try {
                //判断余额
                $newMoney = $balance - $request->post('money');
                if ($newMoney < 0) {
                    return ReturnService::failedReturn('402', '余额不足');
                } else {
                    //扣除用户余额
                    $res = GrUser::where('id', $user_id)->update(['balance' => $newMoney]);
                    if ($res) {
                        //转给商户
                        $data = Orders::join('gr_order_goods', 'order.id', '=', 'gr_order_goods.order_id')
                            ->join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')->where('order.order_sn', $order_sn)->get()->toArray();
                        foreach ($data as $k => $v) {
                            $store = Store::where('id', $v['store_id'])->first();
                            //获取商家id
                            $ress = GrUser::where('id', $store->user_id)
                                ->update(['balance' => GrUser::where('id', $store->user_id)->first()->balance + $request->post('money')]);
                            if ($ress) {
                                //修改订单状态
                                $result = Orders::where('order_sn', $order_sn)->update(['order_status' => 0, 'is_pay' => 1, 'pay_type' => 0]);
                            }
                        }
                    }
                }

                //提交
                Db::commit();
                if ($result) {
                    return ReturnService::successReturn('200', '支付成功', $request->post('money'));
                } else {
                    return ReturnService::failedReturn('400', '支付失败');
                }
            } catch (\Exception $e) {
                //回滚事务
                Db::rollback();
            }
        }

    }

    /**
     * 退款申请
     */
    public function refund(Request $request)
    {
        //获取user_id
        $token = $request->post('token');
        $jwtData = JwtService::decodeToken($token);
        $user_id = $jwtData->data;
        //获取订单id
        $order_id = $request->post('order_id');
        $refund_other_reson = $request->post('refund_other_reson');
        $back_money = $request->post('back_money');
        //获取商户id
        $data = Orders::join('gr_order_goods', 'order.id', '=', 'gr_order_goods.order_id')
            ->join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')
            ->join('gr_store', 'gr_goods.store_id', '=', 'gr_store.id')
            ->where('order.id', $order_id)->first()->toArray();
        $res = GrRefund::insert(['order_id' => $order_id, 'user_id' => $user_id,
            'refund_other_reson' => $refund_other_reson, 'back_money' => $back_money, 'merchant_id' => $data['user_id'], 'refund_other_time' => date('Y-m-d H:i:s')]);
        if ($res) {
            return ReturnService::successReturn('200', '成功', []);
        } else {
            return ReturnService::failedReturn('400', '失败');
        }
    }

    /**

     * 支付策略

     */
    public function order(Request $request){
        $type=$request->get('type');
        $order_sn=$request->get('order_sn');
        $token=$request->get('token');
        $money=$request->get('money');
        $password=$request->get('password');
        switch ($type)
        {
            case "支付宝":

    break;
            case "余额":
                $pay=new Pay(new FullDiscountStrategy());
                $pay->getDiscount($order_sn,$money,$token,$password);
    break;
            default:

        }
    }
}
